package com.nongtai.aspect;

import com.nongtai.annotation.CountUV;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDate;

/**
 * aop实现在方法上统计访问某一资源某天的UV（独立访客）
 * @author yza
 * @version 1.0
 * @date 2024/6/12 22:16
 */
@Component
@Aspect
public class UVAspect {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 统计页面访问的独立用户数（UV）。
     *
     * @param joinPoint
     * @param countUV
     * @return
     * @throws Throwable
     */
    @Around("@annotation(countUV)")
    public Object countUV(ProceedingJoinPoint joinPoint, CountUV countUV) throws Throwable {
        // 从请求中获取当前的HttpServletRequest对象。
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String ip = request.getRemoteAddr();
        // 从CountUV注解中获取页面名称。
        String pageName = countUV.pageName();


        String key = "uv:" + pageName + ":" + LocalDate.now().toString();
        redisTemplate.opsForHyperLogLog().add(key, ip);

        Object result = joinPoint.proceed();

        return result;
    }

}
